package base.thio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class BufferToText {

	private static final int BSIZE = 1024;

	public static void main(String[] args) throws Exception{
		String path="d:a.txt";
		
		FileChannel channel=new FileOutputStream(path).getChannel();
		channel.write(ByteBuffer.wrap("some txt and who the hells are you. ".getBytes()));
		channel.close();
		
		channel=new FileInputStream(path).getChannel();
		ByteBuffer buffer=ByteBuffer.allocate(BSIZE);
		channel.read(buffer);
		buffer.flip();
		System.out.println(buffer.asCharBuffer());
		
		buffer.rewind();
		String encoding=System.getProperty("file.encoding");
		
		System.out.println("Decoded using "+encoding+" : "+Charset.forName(encoding).decode(buffer));
		
		channel=new FileOutputStream(path).getChannel();
		channel.write(ByteBuffer.wrap("some txt and who the hells are you. ".getBytes("UTF-16BE")));
		channel.close();
		
		channel=new FileInputStream(path).getChannel();
		buffer=ByteBuffer.allocate(BSIZE);
		channel.read(buffer);
		buffer.flip();
		System.out.println(buffer.asCharBuffer());
		
		channel=new FileOutputStream(path).getChannel();
		buffer=ByteBuffer.allocate(24);
		buffer.asCharBuffer().put("some text");
		channel.write(buffer);
		channel.close();
		
		channel=new FileInputStream(path).getChannel();
		buffer.clear();
		channel.read(buffer);
		buffer.flip();
		System.out.println(buffer.asCharBuffer());
		
	}
}
